package com.stgl.action;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.stgl.service.BmqkService;
import com.stgl.service.CampusService;
import com.stgl.service.StudentService;
import com.stgl.service.WechartService;
import com.stgl.util.*;
import net.sf.jxls.exception.ParsePropertyException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/wechart")
public class wechart {
    @Resource
    private WechartService wechartService;
    @Resource
    private CampusService campusService;

    @Resource
    private StudentService studentService;

    /**
     * @author 牟明艳
     * @comments 成功获取到openid并进入连接开始业务处理
     * @time 2015-11-17 下午3:07:15
     */
    @RequestMapping("getwxuserinfo.html")
    public @ResponseBody Map<String, Object>getwxuserinfo(HttpServletRequest req){
        String tappid="wx776fd2a0ba81c9c4";
        String tappsecret="2acd5dae5cda61fd3898475141b52748";


       /* wx776fd2a0ba81c9c4
        2acd5dae5cda61fd3898475141b52748*/
        String code = req.getParameter("code");
        //第二步:通过code获取access_token
     /*   ConfKit confkit= new ConfKit("wxpay.properties");*/
//		String urlwx = "https://api.weixin.qq.com/sns/jscode2session?appid="+confkit.get("appid")+"&secret="+confkit.get("appsecret")+"&js_code="+code+"&grant_type=authorization_code";
        String urlwx = "https://api.weixin.qq.com/sns/jscode2session?appid="+tappid+"&secret="+tappsecret+"&js_code="+code+"&grant_type=authorization_code";
        System.out.println("urlwx:"+urlwx);
        String access_token_json = HttpClientUtil.sendGet(urlwx);
        Map<String,String> p_access_token = JSON.parseObject(access_token_json,HashMap.class);
        System.out.println("p_access_token:"+p_access_token);
        String openid = p_access_token.get("openid").toString();
        String session_key = p_access_token.get("session_key").toString();
        Map<String, Object>setmap=new HashMap<String, Object>();
        setmap.put("openid", openid);
        setmap.put("session_key", session_key);
        return setmap;
    }


    /**
     * @author 牟明艳
     * @comments 根据openid查询用户绑定的学生人员有
     * @time 2019年5月27日16:45:35
     */
    @RequestMapping("getuserBindStu.html")
    public @ResponseBody List<Map<String,Object>>getuserBindStu(HttpServletRequest req){
        String openid = req.getParameter("openid");
        Map<String, Object>setmap=new HashMap<String, Object>();
        setmap.put("openid", openid);
        List<Map<String,Object>>list1=wechartService.getuserBindStu(setmap);
        return list1;
    }

    /**
     * @author 牟明艳
     * @comments 查询所有学校
     * @time 2019年5月28日14:06:57
     */
    @RequestMapping("getAllSchool.html")
    public @ResponseBody List<Map<String,Object>>getAllSchool(HttpServletRequest req){
        List<Map<String,Object>>list1=wechartService.getAllSchool();
        return list1;
    }


    /**
     * @author 牟明艳
     * @comments  查看学生是否存在
     * @time 2019年5月28日14:06:57
     */
    @RequestMapping("findStudentExist.html")
    public @ResponseBody List<Map<String,Object>>findStudentExist(HttpServletRequest req){
        Map<String, Object>setmap=new HashMap<String, Object>();
        String csid = req.getParameter("csid");
        setmap.put("csid", csid);
        String sfzh = req.getParameter("sfzh");
        setmap.put("sfzh", sfzh);

        if(req.getParameter("sname")!=null){
            String sname = req.getParameter("sname");
            setmap.put("sname", sname);
        }

        if(req.getParameter("nj")!=null){
            String nj=req.getParameter("nj");
            setmap.put("nj", nj);
        }

        if(req.getParameter("bj")!=null){
            String bj=req.getParameter("bj");
            setmap.put("bj", bj);
        }
        List<Map<String,Object>>list1=wechartService.findStudentExist(setmap);
        return list1;
    }

    /**
     * @author 牟明艳
     * @comments  学生注册
     * @time 2019年5月28日15:03:13
     */
    @RequestMapping("registStudent.html")
    public @ResponseBody void registStudent(HttpServletRequest req){
        String csid = req.getParameter("csid");
        String sfzh = req.getParameter("sfzh");
        String sname = req.getParameter("sname");
        String openid = req.getParameter("openid");

        Map<String, Object>setmap=new HashMap<String, Object>();
        String usid = UUID.randomUUID().toString().replaceAll("-", "");
        setmap.put("usid", usid);
        setmap.put("uname", sfzh);
        setmap.put("role", "0");
        setmap.put("username", sname);
        setmap.put("wxid", openid);
        setmap.put("csid", csid);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        setmap.put("jlxzsj",df.format(new Date()));

        wechartService.registStudent(setmap);
        return ;
    }


    /**
     * @author 牟明艳
     * @comments  查询文化课与社团活动的开设
     * @time 2019年5月28日16:29:47
     */
    @RequestMapping("getCategory.html")
    public @ResponseBody Map<String, Object>getCategory(HttpServletRequest req){
        String csid = req.getParameter("csid");
        String nj = req.getParameter("nj");
        String bj = req.getParameter("bj");
        Map<String, Object>setmap=new HashMap<String, Object>();
        setmap.put("csid", csid);
        setmap.put("nj", nj);
        setmap.put("bj", bj);
        List<Map<String,Object>>list1=wechartService.getWhkCategory(setmap);
        List<Map<String,Object>>list2=wechartService.getStfdCategory(setmap);
        Map<String, Object>gmap=new HashMap<String, Object>();
        gmap.put("whks",list1);
        gmap.put("sthds",list2);
        return gmap;
    }



    /**
     * @author 牟明艳
     * @comments  查询文化课具体信息
     * @time 2019年5月28日16:29:47
     */
    @RequestMapping("whk_list.html")
    public @ResponseBody Map<String, Object>whk_list(HttpServletRequest req){
        String wid = req.getParameter("wid");
        List<Map<String,Object>>list1=wechartService.getWhkDetails(wid);
        Map<String, Object>gmap=new HashMap<String, Object>();
        if(list1.size()>0){
            gmap=list1.get(0);
            List<Map<String,Object>>pris=wechartService.getSfDetails(wid);
            List<Map<String,Object>>teas=wechartService.getTeasDetails(wid);
            gmap.put("pris",pris);
            gmap.put("teas",teas);
        }
        return gmap;
    }

    /**
     * @author 牟明艳
     * @comments  查询社团课具体信息
     * @time 2019年5月28日16:29:47
     */
    @RequestMapping("sthd_list.html")
    public @ResponseBody Map<String, Object>sthd_list(HttpServletRequest req){
        String sid = req.getParameter("sid");
        List<Map<String,Object>>list1=wechartService.getSthdDetails(sid);
        Map<String, Object>gmap=new HashMap<String, Object>();
        if(list1.size()>0){
            gmap=list1.get(0);
            List<Map<String,Object>>pris=wechartService.getSthdSfDetails(sid);
            List<Map<String,Object>>teas=wechartService.getSthdTeasDetails(sid);
            gmap.put("pris",pris);
            gmap.put("teas",teas);
        }
        return gmap;
    }


    /**
     * @author 牟明艳
     * @comments  订单添加
     * @time 2019年5月28日15:03:13
     */
    @RequestMapping("insertOrder.html")
    public @ResponseBody Map<String,Object> insertOrder(HttpServletRequest req){
        Map<String, Object>rmap=new HashMap<String, Object>();
        String sid = req.getParameter("sid");//学生id
        String wid = req.getParameter("wid");//文化课id
        //选择的其他费用
        String priarr = req.getParameter("priarr");
        List<Map<String,String>> listfee = (List<Map<String,String>>) JSONArray.parse(priarr);
        //总费用
        String allprice = req.getParameter("allprice");
        //手续费 总金额的百分几
        String fs3 = req.getParameter("fs3");
        float f1=Float.parseFloat(allprice)*Float.parseFloat(fs3);
        double f2=f1*0.01;
        DecimalFormat f3 = new DecimalFormat(".00");
        String f4=f3.format(f2);


        //报名情况
        String bmqksm = req.getParameter("bmqksm");
        //报名资料
        String urls = req.getParameter("urls");
        //默认审核情况
        String shqk = req.getParameter("shqk");

        List<Map<String,String>> listzl = (List<Map<String,String>>) JSONArray.parse(urls);

        //查询是否已经报名了该辅导班
        Map<String, Object>sfbm=new HashMap<>();
        sfbm.put("sid",sid);
        sfbm.put("wid",wid);
        List<Map<String,Object>>listbb=wechartService.findStuBmqk(sfbm);
        if(listbb.size()>0){
            rmap.put("msg","你已经报名了该辅导班,不能重复报名！");
            rmap.put("result",false);
            return rmap;
        }

        //学生只能报一个辅导班
        List<Map<String,Object>>listotherfdb=wechartService.findStuBmdFdb(sfbm);
        if(listotherfdb.size()>0){
            String mc=listotherfdb.get(0).get("MC").toString();
            rmap.put("msg","你已经报名了"+mc+"！");
            rmap.put("result",false);
            return rmap;
        }

        List<Map<String,Object>>list1=wechartService.getWhkDetails(wid);
        if(list1.size()>0){
            //先查询是否已经超出名额
            List<Map<String,Object>>xelist=wechartService.FindBmqkXe(wid);
            Map<String, Object>getmap=list1.get(0);
            int xe=Integer.parseInt(getmap.get("XE").toString());
            if(xe<=xelist.size()){
                rmap.put("msg","该辅导班报名人数已经满员了！");
                rmap.put("result",false);
                return rmap;
            }

            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            Map<String, Object>bmqk=new HashMap<String, Object>();
            String bid = UUID.randomUUID().toString().replaceAll("-", "");
            bmqk.put("bid",bid);
            bmqk.put("sid",sid);
            bmqk.put("wsid",wid);
            bmqk.put("bmsj",df.format(new Date()));
            bmqk.put("bstate",0+"");
            bmqk.put("shqk",shqk);
            bmqk.put("bmqksm",bmqksm);//报名情况说明
            wechartService.InsertBmqk(bmqk);
            for(int i=0;i<listzl.size();i++){
                String zlid = UUID.randomUUID().toString().replaceAll("-", "");
                Map<String, Object>zlmap=new HashMap<String, Object>();
                zlmap.put("zlid",zlid);
                zlmap.put("bid",bid);
                zlmap.put("url",listzl.get(i).get("imgurl").toString());
                wechartService.InsertBmqkZl(zlmap);
            }

            Map<String, Object>setmap=new HashMap<String, Object>();
            String oid = UUID.randomUUID().toString().replaceAll("-", "");
            setmap.put("oid", oid);
            setmap.put("csid", getmap.get("CSID"));
            setmap.put("nj", getmap.get("NJ"));
            setmap.put("bj", getmap.get("BJ"));
            setmap.put("km", getmap.get("KM"));
            setmap.put("mc", getmap.get("MC"));
            setmap.put("jj", getmap.get("JJ"));
            setmap.put("fy", getmap.get("FY"));
            setmap.put("allprice", allprice);
            setmap.put("sfjf",0+"");
            setmap.put("jlsczt",0+"");
            setmap.put("sid",sid);
            setmap.put("addtime",df.format(new Date()));
            setmap.put("qid",bid);
            setmap.put("sxf",f4);

            wechartService.InsertOrderlist(setmap);
            rmap.put("oid",oid);
            for(int i=0;i<listfee.size();i++){
                Map<String, Object>feemap=new HashMap<String, Object>();
                String ofid = UUID.randomUUID().toString().replaceAll("-", "");
                feemap.put("ofid",ofid);
                feemap.put("xmmc",listfee.get(i).get("XMMC").toString());
                feemap.put("fee",listfee.get(i).get("FEE"));
                feemap.put("oid",oid);
                wechartService.InsertOrderfee(feemap);
            }

            List<Map<String,Object>>listeas=wechartService.getWhkTeaById(wid);
            for(int i=0;i<listeas.size();i++){
                Map<String, Object>teamap=new HashMap<String, Object>();
                String otid = UUID.randomUUID().toString().replaceAll("-", "");
                teamap.put("otid",otid);
                teamap.put("tname",listeas.get(i).get("TNAME").toString());
                teamap.put("jj",listeas.get(i).get("JIANJIE").toString());
                teamap.put("oid",oid);
                wechartService.InsertOrdertea(teamap);
            }
        }
        rmap.put("msg","报名成功！");
        rmap.put("result",true);

        return rmap;
    }




    /*
     * 上传富文本编辑框图片
     */
    @RequestMapping("uploadBmurl.html")
    public  @ResponseBody Map<String, Object> uploadBmurl(HttpServletRequest request, HttpServletResponse response){
        Map<String, Object>param=new HashMap<String, Object>();
        MultipartHttpServletRequest mhsr = (MultipartHttpServletRequest)request;
        if (mhsr == null) {
            return param;
        }
        DiskFileItemFactory fac = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(fac);
        upload.setHeaderEncoding("utf-8");
        try
        {
            mhsr.setCharacterEncoding("utf-8");
        }
        catch (UnsupportedEncodingException e1)
        {
            e1.printStackTrace();
        }
        String se = File.separator;
        String savePath = mhsr.getRealPath("upload") +se+ "bmqk";
        File f1 = new File(savePath);
        if (!f1.exists()) {
            f1.mkdirs();
        }
        String strfile = "";
        try
        {
            Map<String, MultipartFile> files = mhsr.getFileMap();
            for (String key : files.keySet())
            {
                MultipartFile mf = mhsr.getFile(key);
                String name = mf.getOriginalFilename();
                String extName = "";
                if ((name != null) && (!name.trim().equals("")))
                {
                    if (name.lastIndexOf(".") >= 0) {
                        extName = name.substring(name.lastIndexOf("."));
                    }
                    Long fname = Long.valueOf(System.nanoTime());
                    File file = new File(savePath + se + fname + extName);
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    mf.transferTo(file);
                    strfile = "upload\\//bmqk" + "\\//"  + fname + extName;
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        param.put("urls", strfile);
        return param;
    }



    /*
     * 上传学生基本资料
     */
    @RequestMapping("uploadStuurl.html")
    public  @ResponseBody Map<String, Object> uploadStuurl(HttpServletRequest request, HttpServletResponse response){
        Map<String, Object>param=new HashMap<String, Object>();
        MultipartHttpServletRequest mhsr = (MultipartHttpServletRequest)request;
        if (mhsr == null) {
            return param;
        }
        DiskFileItemFactory fac = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(fac);
        upload.setHeaderEncoding("utf-8");
        try
        {
            mhsr.setCharacterEncoding("utf-8");
        }
        catch (UnsupportedEncodingException e1)
        {
            e1.printStackTrace();
        }
        String se = File.separator;
        String savePath = mhsr.getRealPath("upload") +se+ "stu";
        File f1 = new File(savePath);
        if (!f1.exists()) {
            f1.mkdirs();
        }
        String strfile = "";
        try
        {
            Map<String, MultipartFile> files = mhsr.getFileMap();
            for (String key : files.keySet())
            {
                MultipartFile mf = mhsr.getFile(key);
                String name = mf.getOriginalFilename();
                String extName = "";
                if ((name != null) && (!name.trim().equals("")))
                {
                    if (name.lastIndexOf(".") >= 0) {
                        extName = name.substring(name.lastIndexOf("."));
                    }
                    Long fname = Long.valueOf(System.nanoTime());
                    File file = new File(savePath + se + fname + extName);
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    mf.transferTo(file);
                    strfile = "upload\\//bmqk" + "\\//"  + fname + extName;
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        param.put("urls", strfile);
        return param;
    }

/**
 * @author 牟明艳
 * @comments  订单添加
 * @time 2019年5月28日15:03:13
 */
    @RequestMapping("insertOrderSthd.html")
    public @ResponseBody Map<String,Object> insertOrderSthd(HttpServletRequest req){
        Map<String, Object>rmap=new HashMap<String, Object>();
        String sid = req.getParameter("sid");//学生id
        String wsid = req.getParameter("wsid");//社团活动课id
        String shqk = req.getParameter("shqk");//默认审核情况

        //选择的其他费用
        String priarr = req.getParameter("priarr");
        List<Map<String,String>> listfee = (List<Map<String,String>>) JSONArray.parse(priarr);
        //总费用
        String allprice = req.getParameter("allprice");
        //手续费 总金额的百分几
        String fs3 = req.getParameter("fs3");
        float f1=Float.parseFloat(allprice)*Float.parseFloat(fs3);
        double f2=f1*0.01;
        DecimalFormat zhje = new DecimalFormat(".00");
        String f3=zhje.format(f2);

        //报名情况
        String bmqksm = req.getParameter("bmqksm");
        //报名资料
       String urls = req.getParameter("urls");
        List<Map<String,String>> listzl = (List<Map<String,String>>) JSONArray.parse(urls);

        //查询是否已经报名了该辅导班
        Map<String, Object>sfbm=new HashMap<>();
        sfbm.put("sid",sid);
        sfbm.put("wid",wsid);
        List<Map<String,Object>>listbb=wechartService.findStuBmqk(sfbm);
        if(listbb.size()>0){
            rmap.put("msg","你已经报名了该辅导班,不能重复报名！");
            rmap.put("result",false);
            return rmap;
        }

        List<Map<String,Object>>list1=wechartService.getSthdDetails(wsid);
        if(list1.size()>0){
            //先查询是否已经超出名额
            List<Map<String,Object>>xelist=wechartService.FindBmqkXe(wsid);
            Map<String, Object>getmap=list1.get(0);
            int xe=Integer.parseInt(getmap.get("XE").toString());
            if(xe<=xelist.size()){
                rmap.put("msg","该辅导班报名人数已经满员了！");
                rmap.put("result",false);
                return rmap;
            }

            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            Map<String, Object>bmqk=new HashMap<String, Object>();
            String bid = UUID.randomUUID().toString().replaceAll("-", "");
            bmqk.put("bid",bid);
            bmqk.put("sid",sid);
            bmqk.put("wsid",wsid);
            bmqk.put("bmsj",df.format(new Date()));
            bmqk.put("bstate",0+"");
            bmqk.put("shqk",shqk);
            bmqk.put("bmqksm",bmqksm);
            wechartService.InsertBmqk(bmqk);

            Map<String, Object>setmap=new HashMap<String, Object>();
            String oid = UUID.randomUUID().toString().replaceAll("-", "");
            setmap.put("oid", oid);
            setmap.put("csid", getmap.get("CSID"));
            setmap.put("mc", getmap.get("MC"));
            setmap.put("jj", getmap.get("JJ"));
            setmap.put("fy", getmap.get("FY"));
            setmap.put("allprice", allprice);
            setmap.put("sfjf",0+"");
            setmap.put("jlsczt",0+"");
            setmap.put("sid",sid);
            setmap.put("addtime",df.format(new Date()));
            setmap.put("qid",bid);
            setmap.put("sxf",f3);
            wechartService.InsertOrderlist(setmap);

            for(int i=0;i<listfee.size();i++){
                Map<String, Object>feemap=new HashMap<String, Object>();
                String ofid = UUID.randomUUID().toString().replaceAll("-", "");
                feemap.put("ofid",ofid);
                feemap.put("xmmc",listfee.get(i).get("XMMC").toString());
                feemap.put("fee",listfee.get(i).get("FEE"));
                feemap.put("oid",oid);
                wechartService.InsertOrderfee(feemap);
            }

            List<Map<String,Object>>listeas=wechartService.getSthdTeasDetails(wsid);
            for(int i=0;i<listeas.size();i++){
                Map<String, Object>teamap=new HashMap<String, Object>();
                String otid = UUID.randomUUID().toString().replaceAll("-", "");
                teamap.put("otid",otid);
                teamap.put("tname",listeas.get(i).get("TNAME").toString());
                teamap.put("jj",listeas.get(i).get("JIANJIE").toString());
                teamap.put("oid",oid);
                wechartService.InsertOrdertea(teamap);
            }

            for(int i=0;i<listzl.size();i++){
                String zlid = UUID.randomUUID().toString().replaceAll("-", "");
                Map<String, Object>zlmap=new HashMap<String, Object>();
                zlmap.put("zlid",zlid);
                zlmap.put("bid",bid);
                zlmap.put("url",listzl.get(i).get("imgurl").toString());
                wechartService.InsertBmqkZl(zlmap);
            }

            rmap.put("oid",oid);
        }

        rmap.put("result",true);
        rmap.put("msg","报名成功！");
        return rmap;
    }





    /**
     * @author 牟明艳
     * @comments 购买 提交订单
     * @time 2017年12月15日10:39:37
     */
    @RequestMapping("submitorder.html")
    public @ResponseBody Map<String, Object> submitorder(HttpServletRequest req){
        String orderid = req.getParameter("oid");
        String wxid = req.getParameter("wxid");
        String ordername = req.getParameter("ordername");


        //手续费 总金额的百分几
        String allprice = req.getParameter("allprice");//总价格
        String fs3 = req.getParameter("fs3");//手续费占百分几
        float f1=Float.parseFloat(allprice)*Float.parseFloat(fs3);
        double f2=f1*0.01;
        double zje=Double.parseDouble(allprice)+f2;
        DecimalFormat zhje = new DecimalFormat(".00");
        String zjg=zhje.format(zje);


        String ip = req.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = req.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = req.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = req.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = req.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = req.getRemoteAddr();
        }

        //支付
        Map<String, Object>paymap=new HashMap<String, Object>();
        long timeStamp_=System.currentTimeMillis();   //时间戳
        String payurl="https://api.mch.weixin.qq.com/pay/unifiedorder";
        String timeStamp=String.valueOf(timeStamp_);

        //金额转换
        float floatmonye=Float.parseFloat(zjg)*100;
        int Moneys=(int)floatmonye;
        SortedMap<String, Object>  treeMap = new TreeMap<String, Object>();

        String nonce_str=PayCommonUtil.CreateNoncestr();
        ConfKit confkit= new ConfKit("wxpay.properties");
        treeMap.put("appid",confkit.get("appid"));// 微信分配的小程序ID
        treeMap.put("body", "柒彩教育-"+ordername);  //商品简单描述  商家名称-销售商品类目
        treeMap.put("detail", "柒彩教育-"+ordername);  //单品优惠字段v
        treeMap.put("mch_id", confkit.get("mch_id")); //微信支付分配的商户号
        treeMap.put("nonce_str",nonce_str); //随机字符串，不长于32位。
        treeMap.put("notify_url", confkit.get("notify_url")+"/wechart/notify.html");  //接收微信支付异步通知回调地址
        treeMap.put("openid",wxid); //用户在商户appid下的唯一标识。openid如何获取
        treeMap.put("out_trade_no",orderid);  //商户系统内部的订单号
        treeMap.put("spbill_create_ip", ip);
        treeMap.put("total_fee", Moneys+"");  //订单总金额，单位为分
        treeMap.put("trade_type", "JSAPI"); //交易类型
        String sign=PayCommonUtil.createSign(treeMap,confkit);//生成签名的方法
        treeMap.put("sign", sign);  //签名

        String xmltreemap="<xml>"+
                "<appid>"+confkit.get("appid")+"</appid>"+
                "<body>柒彩教育-"+ordername+"</body>"+
                "<detail>柒彩教育-"+ordername+"</detail>"+
                "<mch_id>"+confkit.get("mch_id")+"</mch_id>"+
                "<nonce_str>"+nonce_str+"</nonce_str>"+
                "<notify_url>"+confkit.get("notify_url")+"/wechart/notify.html"+"</notify_url>"+
                "<openid>"+wxid+"</openid>"+
                "<out_trade_no>"+orderid+"</out_trade_no>"+
                "<spbill_create_ip>"+ip+"</spbill_create_ip>"+
                "<total_fee>"+Moneys+""+"</total_fee>"+
                "<trade_type>JSAPI</trade_type>"+
                "<sign>"+sign+"</sign>"+
                "</xml>";
        String prepay_id= GetWxOrderno.getPayNo(payurl, xmltreemap);

        //再次签名
        String sb="appId="+confkit.get("appid")+"&";
        sb+="nonceStr="+nonce_str+"&";
        sb+="package=prepay_id="+prepay_id+"&";
        sb+="signType=MD5&timeStamp="+timeStamp+"&";
        sb+="key="+confkit.get("key");

        String paysign = MD5Util.MD5Encode(sb.toString(),"UTF-8").toUpperCase();
        paymap.put("timeStamp", timeStamp);
        paymap.put("nonceStr", nonce_str);
        paymap.put("prepay_id", prepay_id);
        paymap.put("sign", paysign);
        paymap.put("orderid", orderid);

        System.out.println("paymap:"+paymap);
        return paymap;
    }

    /**
     * @author 牟明艳
     * @comments  查看学校详情
     * @time 2019年5月30日17:44:14
     */
    @RequestMapping("getSchoolDetail.html")
    public @ResponseBody Map<String,Object>getSchoolDetail(HttpServletRequest req){
        String csid = req.getParameter("csid");
        Map<String,Object>rmap=campusService.getCampusBycsid(csid);
        return rmap;
    }


    /**
     * @author 牟明艳
     * @comments  修改学生信息
     * @time 2019年5月30日20:02:43
     */
    @RequestMapping("EditStudent.html")
    public @ResponseBody void EditStudent(HttpServletRequest req){
        String sid = req.getParameter("sid");
        String sname = req.getParameter("sname");
        String nj = req.getParameter("nj");
        String bj = req.getParameter("bj");
        String sfzh = req.getParameter("sfzh");
        String osfzh = req.getParameter("osfzh");

        Map<String, Object>setmap=new HashMap<String, Object>();
        setmap.put("sid", sid);
        setmap.put("sname", sname);
        setmap.put("nj", nj);
        setmap.put("bj", bj);
        setmap.put("sfzh", sfzh);
        setmap.put("osfzh", osfzh);
        wechartService.EditStudent(setmap);
        return ;
    }


    /**
     * @author 牟明艳
     * @comments 订单列表
     * @time 2019年6月3日13:37:56
     */
    @RequestMapping("orderList.html")
    public @ResponseBody Map<String, Object>orderList(HttpServletRequest req){
        String page = req.getParameter("page");//页数
        if(page==null || page.trim().equals("")){
            page="1";
        }
        String limit = req.getParameter("limit");//每页条数
        if(limit==null || limit.trim().equals("")){
            limit="10";
        }
        String type = req.getParameter("dtype");//查询类别

        String sfjf ="";//是否缴费 是否缴费 0：未缴费 1缴费
        String cancel ="";//是否取消 0：未取消 1取消
        String shqk="";//审核情况 0未审核 1审核通过 2审核未通过
        String bstate="0";//默认查询未取消的
        if(type.equals("dfk")){
            //未付款
            sfjf="0";
        }else if(type.equals("dpj")){
            //已付款
            sfjf="1";
        }else if(type.equals("yqx")){
            //已取消
            cancel="1";
            bstate="1";
        }else if(type.equals("wsh")){
            //未审核
            shqk="0";
        }else if(type.equals("shtg")){
            //审核通过
            shqk="1";
        }else if(type.equals("shwtg")){
            //审核通过
            shqk="2";
        }

        String sid = req.getParameter("sid");//学生id
        Map<String, Object>getmap=new HashMap<String, Object>();
        Integer end=Integer.parseInt(page)*Integer.parseInt(limit);
        Integer start=end-10;
        getmap.put("start", start);
        getmap.put("end", end);
        getmap.put("sid", sid);
        getmap.put("sfjf", sfjf);
        getmap.put("cancel", cancel);
        getmap.put("shqk", shqk);
        getmap.put("bstate", bstate);

        //查询订单详情
        List<Map<String, Object>>lisorder=new ArrayList<Map<String,Object>>();
        lisorder=wechartService.orderList(getmap);
        Map<String, Object>ordermap=new HashMap<String, Object>();
        ordermap.put("items", lisorder);

        //查询订单总数
        Integer total=0;
        total=wechartService.orderCount(getmap);
        getmap.put("total", total);
        ordermap.put("paginate", getmap);
        return ordermap;
    }


    /**
     * @author 牟明艳
     * @comments  删除订单
     * @time 2019年6月3日19:10:20
     */
    @RequestMapping("delOrder.html")
    public @ResponseBody void delOrder(HttpServletRequest req){
        String oid = req.getParameter("oid");

        Map<String, Object>setmap=new HashMap<String, Object>();
        setmap.put("oid", oid);

        wechartService.delOrder(setmap);


        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        setmap.put("cacelsj",df.format(new Date()));
        setmap.put("bstate", "1");
        wechartService.updatebmqktocancel(setmap);
        return ;
    }


    /**
     * @author 牟明艳
     * @comments  取消订单
     * @time 2019年6月3日19:10:59
     */
    @RequestMapping("cancelOrder.html")
    public @ResponseBody void cancelOrder(HttpServletRequest req){
        String oid = req.getParameter("oid");

        Map<String, Object>setmap=new HashMap<String, Object>();
        setmap.put("oid", oid);
        wechartService.cancelOrder(setmap);

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        setmap.put("cacelsj",df.format(new Date()));
        setmap.put("bstate", "1");
        wechartService.updatebmqktocancel(setmap);
        return ;
    }


    /**
     * @author 牟明艳
     * @comments 订单详情
     * @time 2019年6月3日19:33:12
     */
    @RequestMapping("orderWhk_list.html")
    public @ResponseBody Map<String, Object>orderWhk_list(HttpServletRequest req){
        String oid = req.getParameter("oid");
        Map<String, Object>ordermap=new HashMap<String, Object>();
        ordermap=wechartService.orderWhk_list(oid);
        return ordermap;
    }


    /**
     * @author 牟明艳
     * @comments 修改交易成功
     * @time 2019年6月3日19:33:12
     */
    @RequestMapping("paysuccess.html")
    public @ResponseBody void  paysuccess(HttpServletRequest req){
        String oid = req.getParameter("oid");
        String prepay_id = req.getParameter("prepay_id");
        Map<String, Object>ordermap=new HashMap<String, Object>();
        ordermap.put("oid",oid);
        ordermap.put("prepay_id",prepay_id);
        wechartService.paysuccess(ordermap);
    }



    /**
     * @author 牟明艳
     * @comments  查看学生是否存在
     * @time 2019年6月15日14:06:24
     */
    @RequestMapping("getOrderInfoByid.html")
    public @ResponseBody List<Map<String,Object>>getOrderInfoByid(HttpServletRequest req){
        String oid = req.getParameter("oid");
        Map<String, Object>setmap=new HashMap<String, Object>();
        setmap.put("oid", oid);
        List<Map<String,Object>>list1=wechartService.getOrderInfoByid(setmap);
        return list1;
    }


    /**
     * @author 牟明艳
     * @comments 添加购物车
     * @time 2017年10月25日18:50:05
     */
    @RequestMapping("notify.html")
    public @ResponseBody void notify(HttpServletRequest req){
        System.out.print("微信支付回调数据开始");
        //示例报文
        String inputLine;
        String notityXml = "";
        String resXml = "";
        try {
            while ((inputLine = req.getReader().readLine()) != null) {
                notityXml += inputLine;
            }
            req.getReader().close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("接收到的报文：" + notityXml);

        System.out.println("微信支付回调数据结束");
        return ;
    }




    /**
     * @author 牟明艳
     * @comments  新增入学学生
     * @time 2019年7月24日17:43:27
     */
    @RequestMapping("insertNewStudent.html")
    public @ResponseBody Map<String,Object> insertNewStudent(HttpServletRequest req){
        Map<String, Object>rmap=new HashMap<String, Object>();
        String csid = req.getParameter("csid");//学校id
        String sname = req.getParameter("sname");//姓名
        String sfzh = req.getParameter("sfzh");//身份证号
        String jzxm = req.getParameter("jzxm");//家长姓名
        String jzsj = req.getParameter("jzsj");//家长手机
        String hjszd = req.getParameter("hjszd");//户籍所在地
        String urls = req.getParameter("urls");//图片
        String wxid = req.getParameter("wxid");//微信id
        //验证身份证是否正确
        boolean va= OIDCardUtil.validateCard(sfzh);
        if(!va){
            rmap.put("result",false);
            rmap.put("msg","身份证不合法");
            return rmap;
        }
        String sid = UUID.randomUUID().toString().replaceAll("-", "");
        rmap.put("sid",sid);
        rmap.put("csid",csid);
        rmap.put("sname",sname);
        rmap.put("sfzh",sfzh);
        rmap.put("nj","1");
        rmap.put("sstate","0");
        rmap.put("jzxm",jzxm);
        rmap.put("jzsj",jzsj);
        rmap.put("hjszd",hjszd);
        String birth=OIDCardUtil.getBirthByIdCard(sfzh);
        rmap.put("birth",birth);
        String sex=OIDCardUtil.getGenderByIdCard(sfzh);
        rmap.put("sex",sex);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        rmap.put("jlxzsj",df.format(new Date()));

        List<String> listr = (List<String>) JSONArray.parse(urls);
        for(int k=0;k<listr.size();k++){
            Map<String, Object>zmap=new HashMap<String, Object>();
            String zlid = UUID.randomUUID().toString().replaceAll("-", "");
            zmap.put("zlid",zlid);
            zmap.put("sid",sid);
            zmap.put("url",listr.get(k).toString());
            int m=studentService.Insert_stufile(zmap);
            if(m<0){
                rmap.put("result",false);
                rmap.put("msg","图片上传失败!");
                return rmap;
            }
        }
        int m=studentService.Insert_Student(rmap);
        if(m<0){
            rmap.put("result",false);
            rmap.put("msg","图片上传失败!");
            return rmap;
        }else if(m==3){
            rmap.put("result",false);
            rmap.put("msg","该学生已经报名,不能重复报名!");
            return rmap;
        }else{
            Map<String, Object>uamap=new HashMap<String, Object>();
            String usid = UUID.randomUUID().toString().replaceAll("-", "");
            uamap.put("usid", usid);
            uamap.put("uname", sfzh);
            uamap.put("role", "0");
            uamap.put("username", sname);
            uamap.put("wxid", wxid);
            uamap.put("csid", csid);
            uamap.put("jlxzsj",df.format(new Date()));
            wechartService.registStudent(uamap);
        }
        rmap.put("result",true);
        rmap.put("msg","保存成功!");
        return rmap;
    }


}
